package top.leyi.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.leyi.IService.IPushService;
import top.leyi.IService.ITalkService;
import top.leyi.entity.Talk.SimpleTalk;
import top.leyi.entity.Talk.Talk;
import top.leyi.entity.pushAndColle.Push;
import top.leyi.entity.user.User;
import top.leyi.exception.TalkNotFoundException;
import top.leyi.mapper.PushMapper;
import top.leyi.mapper.TalkMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PushServiceImpl implements IPushService {
    @Autowired
    TalkMapper talkMapper;
    @Autowired
    PushMapper pushMapper;

    @Override
    public Map<String, List<Push>> getAllPush(User user) {
        List<Push> list = pushMapper.getOwnPush(user.getId());
        Map<String, List<Push>> map = new HashMap<>();

        for(Push push : list) {
            if(!map.containsKey(push.getType())){
                map.put(push.getType(), new ArrayList<Push>());
            }
            map.get(push.getType()).add(push);
        }

        return map;
    }

    @Override
    public  List<SimpleTalk> getSysPush(int id) {
        List<Push> pushes = pushMapper.getSysPush(id);
        List<SimpleTalk> talks = new ArrayList<>();

        for (Push push : pushes) {
            SimpleTalk simpleTalk = talkMapper.queryDeathTalk(push.getOriginal());
            simpleTalk.setId(push.getId());
            talks.add(simpleTalk);
        }
        return talks ;
    }

    @Override
    public void removePush(Push push, User user) {
        pushMapper.removePush(push);
    }

    @Override
    @Transactional
    public void addOnePush(  Talk talk  )   throws TalkNotFoundException{
         addOnePush(talk, 0);
    }
    @Override
    /**
     * @添加一个单播消息
     * @param talk
     * @param user
     * @param destId
     * @throws TalkNotFoundException
     */
    @Transactional
    public void addOnePush( Talk talk,  int destId)   throws TalkNotFoundException{

        talkMapper.addDeathTalk(talk);
        talk = talkMapper.queryDeathTalkWithUserId(talk.getUser_id());

        if(talk == null) {
            throw new TalkNotFoundException();
        }
        Push push = new Push();
        push.setOriginal(talk.getId());
        push.setDest(destId);
        push.setType("系统通知");
        pushMapper.addPush(push);
    }
}
